package com.thti.mecool.client.model.biz;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;

import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.db.DataBase;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;

public class PlanBizImpl {

	private DataBase dataBase;

	public PlanBizImpl(Context context) {
		dataBase = new DataBase(context);
	}

	public void save(PlanClient planClient) {
		String sqlString = "insert into plan(userId ,planId,planName,isFlag,isType,planTime,status,denyNotes ,changeNotes,type,createTime) values(?,?,?,?,?,?,?,?,?,?,?)";
		dataBase.execObject(
				sqlString,
				new String[] { planClient.getUserId(), planClient.getPlanId(),
						planClient.getPlanName(),
						String.valueOf(planClient.getIsFlag()),
						String.valueOf(planClient.getIsType()),
						planClient.getPlanTime(), planClient.getStatus(),
						planClient.getDenyNotes(), planClient.getChangeNotes(),
						planClient.getType(),
						String.valueOf(planClient.getCreateTime()) });
		dataBase.close();
	}

	public void updateDraftPlanId(String key, String planId) {
		String[] sqls = new String[] {
				"update task set planId=?,isType='local' where planId=?",
				"update plan set planId=?,status='new',isType=2 where planId=?",
				"update project set planId=? where planId=?" };
		for (String s : sqls) {
			dataBase.execObject(s, new String[] { planId, key });
		}
	}

	public void update(PlanClient planClient) {
		String sqlString = "update plan set planName=? where planId=?";
		dataBase.execObject(sqlString, new String[] { planClient.getPlanName(),
				planClient.getPlanId() });
		dataBase.close();
	}

	// public void deleteByPlanId(String planId){
	// String sqlString="delete from plan  where planId=?";
	// dataBase.execObject(sqlString, new String[]{planId});
	// dataBase.close();
	// }

	public void delete(String planId, boolean flag) {
		dataBase.getWritableDatabase().beginTransaction();// 开始事务
		try {
			dataBase.getWritableDatabase()
					.execSQL("delete from plan  where planId=?",
							new String[] { planId });
			dataBase.getWritableDatabase().execSQL(
					"delete from  project where planId=?",
					new String[] { planId });
			dataBase.getWritableDatabase()
					.execSQL("delete from  task where planId=?",
							new String[] { planId });
			if (flag) {
				dataBase.getWritableDatabase().execSQL(
						"delete  from taskStep where planId=?",
						new Object[] { planId });
			}
			dataBase.getWritableDatabase().setTransactionSuccessful();// 调用此方法会在执行到endTransaction()
																		// 时提交当前事务，如果不调用此方法会回滚事务
		} finally {
			dataBase.getWritableDatabase().endTransaction();// 由事务的标志决定是提交事务，还是回滚事务
		}
		dataBase.getWritableDatabase().close();
	}

	public boolean deletePlanForDate(String date){
		String sql="delete from plan where planTime<=? AND isType!=1"; 
		boolean flag=dataBase.execObject(sql, new String[]{date});
		dataBase.close();
		return flag;
	}
	
	public void deleteProjectAndTask(String planId, String userId) {
		if(findTaskForPlan(planId))
		dataBase.execObject("delete from task  where planId=? AND userId=?", new String[] {
				planId, userId });
		if(findProjectForPlan(planId))
		dataBase.execObject("delete from project  where planId=? AND userId=?",
				new String[] { planId, userId });
		dataBase.close();
	}

	public boolean findTaskForPlan(String planId) {
		Cursor cursor = dataBase.getWritableDatabase().rawQuery(
				"select * from task where planId=?", new String[] { planId });
		int i = 0;
		while (cursor.moveToNext()) {
			i++;
		}
		cursor.close();
		if (i > 0)
			return true;
		return false;
	}
	public boolean findProjectForPlan(String planId) {
		Cursor cursor = dataBase.getWritableDatabase().rawQuery(
				"select * from project where planId=?", new String[] { planId });
		int i = 0;
		while (cursor.moveToNext()) {
			i++;
		}
		cursor.close();
		if (i > 0)
			return true;
		return false;
	}

	public void deleteProject(String planId, String projectId, String taskId) {
		dataBase.getWritableDatabase().beginTransaction();// 开始事务
		try {
			dataBase.getWritableDatabase().execSQL(
					"delete from plan  where planId!=?",
					new String[] { planId });
			dataBase.getWritableDatabase().execSQL(
					"delete from  project where planId!=? AND projectId!=?",
					new String[] { planId, projectId });
			dataBase.getWritableDatabase()
					.execSQL(
							"delete from  task where planId!=? AND projectId!=? AND taskId !=?",
							new String[] { planId, projectId, taskId });
			dataBase.getWritableDatabase().setTransactionSuccessful();// 调用此方法会在执行到endTransaction()
																		// 时提交当前事务，如果不调用此方法会回滚事务
		} finally {
			dataBase.getWritableDatabase().endTransaction();// 由事务的标志决定是提交事务，还是回滚事务
		}
		dataBase.getWritableDatabase().close();
	}

	public int findPlanId() {
		String sqlString = "select  id from  plan order by createTime DESC  limit 0,1";
		Cursor cursor = dataBase.queryObject(sqlString, new String[] {});
		int i = 0;
		while (cursor.moveToNext()) {
			i = cursor.getInt(0);
		}
		if (i == 0) {
			dataBase.execObject("update sqlite_sequence set plan=0",
					new String[] {});
		}
		cursor.close();
		dataBase.close();
		return i == 0 ? 1 : i + 1;
	}

	public int findPlanCount(int isType, String userId) {
		String sqlString = "select count(*) id from plan where isType=? and userId=?";
		Cursor cursor = dataBase.queryObject(sqlString,
				new String[] { String.valueOf(isType), userId });
		int i = 0;
		while (cursor.moveToNext()) {
			i = cursor.getInt(cursor.getColumnIndex("id"));
		}
		cursor.close();
		dataBase.close();
		return i;
	}

	public boolean findPlanIdIsexist(String planId, String userId) {
		String sql = "select planId from plan where isType=2 and planId=? and userId=?";
		Cursor cursor = dataBase.getReadableDatabase().rawQuery(sql,
				new String[] { planId, userId });
		int i = 0;
		while (cursor.moveToNext()) {
			i++;
		}
		if (i > 0)
			return true;
		return false;
	}

	public PlanClient findByPlanId(int isType, int id, String userId) {

		String sql = "select  * from plan where isType=? and planId=? and  userId=?";
		PlanClient PlanClient = (PlanClient) dataBase.findByObject(
				PlanClient.class, sql, new String[] { String.valueOf(isType),
						String.valueOf(id), userId });
		dataBase.close();

		return PlanClient;
	}

	public PlanClient findUploadPlan(int id, String userId) {

		String sql = "select  * from plan where  planId=? and  userId=?";
		PlanClient PlanClient = (PlanClient) dataBase.findByObject(
				PlanClient.class, sql, new String[] { String.valueOf(id),
						userId });
		dataBase.close();
		return PlanClient;
	}

	/**
	 * 计划管理
	 * 
	 * @param PlanClientTime
	 * @return
	 */
	public PlanClient findByPlanDate(String PlanClientTime, String userId) {
		String sql = "select  * from plan where isType=1 and planTime=? and  userId=?";

		PlanClient PlanClient = (PlanClient) dataBase.findByObject(
				PlanClient.class, sql, new String[] { PlanClientTime, userId });
		dataBase.close();
		return PlanClient;
	}

	@SuppressWarnings("unchecked")
	public List<PlanClient> findAll() {
		// select
		// pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime
		// from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND
		// pro.id=t.projectId
		String sql = "select  * from plan where isType=0  order by createTime DESC ";
		List<PlanClient> list = dataBase.findAll(PlanClient.class, sql,
				new String[] {});
		dataBase.close();
		return list;
	} 
	@SuppressWarnings("unchecked")
	public boolean planIsexistDate(String planTime){
		String sql = "select * from plan where planTime=? and isType<>0 order by createTime DESC ";
		List<PlanClient> list = dataBase.findAll(PlanClient.class, sql,
				new String[] {planTime});
		return list.size()>0?true:false;
	}
	
	@SuppressWarnings("unchecked")
	public List<PlanClient> findMyPlanAll(String userId) {
		// select
		// pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime
		// from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND
		// pro.id=t.projectId
		String sql = "select  * from plan where isType=2 AND userId=? order by createTime DESC ";
		List<PlanClient> list = dataBase.findAll(PlanClient.class, sql,
				new String[] { userId });
		dataBase.close();
		return list;
	}

	/**
	 * 判断projrctId是已经存在
	 * 
	 * @param id
	 * @return
	 */
	public boolean findByPlanId(String planId, int userId) {
		String sqlString = "select  * from plan where planId=? AND userId=?";
		Cursor cursor = dataBase.queryObject(sqlString, new String[] { planId,
				String.valueOf(userId) });
		while (cursor.moveToNext()) {
			boolean flag = cursor.getLong(0) > 0 ? true : false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	}

	public boolean findByProjectId(String planId, String projectId, int userId) {
		String sqlString = "select  * from project where planId=? AND projectId=? AND userId=?";
		System.out.println("select  * from project where planId='"+planId+"' AND projectId='"+projectId+"' AND userId='"+userId+"'");
		Cursor cursor = dataBase.queryObject(sqlString, new String[] { planId,
				projectId, String.valueOf(userId) });
		while (cursor.moveToNext()) {
			boolean flag = cursor.getLong(0) > 0 ? true : false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	}

	public boolean findByTaskId(String planId, String projectId, String taskId,
			int userId) {
		String sqlString = "select  * from task where planId=? AND projectId=? AND taskId=? AND userId=?";
		Cursor cursor = dataBase.queryObject(sqlString, new String[] { planId,
				projectId, taskId, String.valueOf(userId) });
		while (cursor.moveToNext()) {
			boolean flag = cursor.getLong(0) > 0 ? true : false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	}

	public void savePlan(List<Map<String, Object[]>> list) {
		dataBase.getWritableDatabase().beginTransaction();// 开始事务
		if (list != null && list.size() > 0) {
			try {
				Util.print("size:   " + list.size());
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).containsKey(HandlerConstant.PLAN_SQL)) {
						Util.print(HandlerConstant.PLAN_SQL + ":   "
								+ list.get(i).get(HandlerConstant.PLAN_SQL));
						dataBase.getWritableDatabase().execSQL(
								HandlerConstant.PLAN_SQL,
								list.get(i).get(HandlerConstant.PLAN_SQL));
					} else if (list.get(i).containsKey(
							HandlerConstant.PROJECT_SQL)) {
						// Util.print(HandlerConstant.PROJECT_SQL+":   "+list.get(i).get(HandlerConstant.PROJECT_SQL));
						dataBase.getWritableDatabase().execSQL(
								HandlerConstant.PROJECT_SQL,
								list.get(i).get(HandlerConstant.PROJECT_SQL));
					} else if (list.get(i)
							.containsKey(HandlerConstant.TASK_SQL)) {
						// Util.print(HandlerConstant.TASK_SQL+":   "+list.get(i).get(HandlerConstant.TASK_SQL));
						dataBase.getWritableDatabase().execSQL(
								HandlerConstant.TASK_SQL,
								list.get(i).get(HandlerConstant.TASK_SQL));
					} else if (list.get(i).containsKey(
							HandlerConstant.TASK_STEP_SQL)) {
						 Util.print(HandlerConstant.TASK_STEP_SQL+":   "+list.get(i).get(HandlerConstant.TASK_STEP_SQL));
						dataBase.getWritableDatabase().execSQL(
								HandlerConstant.TASK_STEP_SQL,
								list.get(i).get(HandlerConstant.TASK_STEP_SQL));
					} else if (list.get(i).containsKey(
							HandlerConstant.TASKITEM_STEP_SQL)) {
						dataBase.getWritableDatabase().execSQL(
								HandlerConstant.TASKITEM_STEP_SQL,
								list.get(i).get(HandlerConstant.TASKITEM_STEP_SQL));
					}
				}
				dataBase.getWritableDatabase().setTransactionSuccessful();// 调用此方法会在执行到endTransaction()
																			// 时提交当前事务，如果不调用此方法会回滚事务
			} finally {
				dataBase.getWritableDatabase().endTransaction();// 由事务的标志决定是提交事务，还是回滚事务
			}
		}
		dataBase.getWritableDatabase().close();
	}

	@SuppressWarnings("unchecked")
	public void deletePlans(String date) {
		Date d=new Date(System.currentTimeMillis());
		Calendar c=Calendar.getInstance();
		c.add(Calendar.DATE,   -3);
		String s=TimeUtil.dateToString(c.getTime(), 4);
		System.out.println(s);
		String sql=null;
		List<PlanClient> list=new ArrayList<PlanClient>();
			sql="select  * plan where ?<=planTime order by type ISNULL";
			list.addAll(dataBase.findAll(PlanClient.class, sql,
					new String[] { s}));
			for(PlanClient pc:list){
				String planId=pc.getPlanId();
				delete(planId, true);
			}
		dataBase.close();
	}
	public List<PlanClient> findByType(String date) {
		Date d=new Date(System.currentTimeMillis());
		Calendar c=Calendar.getInstance();
		c.add(Calendar.DATE,   -1);
		String s=TimeUtil.dateToString(c.getTime(), 4);
		System.out.println(s);
		String sql=null;
		List<PlanClient> list=null;
		if(d.getHours()<7){
			sql="select  * from plan where isType=1 and ?<=planTime AND planTime<=? order by type ISNULL";
			list = dataBase.findAll(PlanClient.class, sql,
					new String[] { s,date });
		}
		else{
		sql = "select  * from plan where isType=1 and planTime=? order by type ISNULL";
		list = dataBase.findAll(PlanClient.class, sql,
				new String[] { date });}
		dataBase.close();
		return list != null ? list : new ArrayList<PlanClient>();
	}

	/**
	 * 查询变更或退回的计划
	 * 
	 * @param isType
	 * @param planTime
	 * @return
	 */
	public PlanClient findByType(int isType, String planId, String userId) {
		// select
		// pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime
		// from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND
		// pro.id=t.projectId
		String sql = "select  * from plan where isType=? and planId=? and userId=? order by createTime DESC ";
		PlanClient planClient = (PlanClient) dataBase.findByObject(
				PlanClient.class, sql, new String[] { String.valueOf(isType),
						planId, userId });
		dataBase.close();
		return planClient;
	}
}
